package com.jeeplus.test.jlnu.teachingArchive.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.jeeplus.core.pdf.Documents4jUtil;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.jlnu.archivalInfo.domain.entity.ArchivalInfo;
import com.jeeplus.test.jlnu.archivalInfo.mapper.ArchivalInfoMapper;
import com.jeeplus.test.jlnu.changeStuInfo.domain.entity.ChangeStuInfo;
import com.jeeplus.test.jlnu.changeStuInfo.mapper.ChangeStuInfoDetailMapper;
import com.jeeplus.test.jlnu.graduationInfo.domain.entity.NewGraduationInfo;
import com.jeeplus.test.jlnu.graduationInfo.mapper.NewGraduationInfoMapper;
import com.jeeplus.test.jlnu.teachingArchive.domain.entity.AcademicInfo;
import com.jeeplus.test.jlnu.teachingArchive.domain.vo.AcademicInfoVo;
import com.jeeplus.test.jlnu.teachingArchive.mapper.AcademicInfoMapper;
import com.jeeplus.test.jlnu.teachingArchive.service.AcademicInfoService;
import liquibase.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//教学档案基础信息实现类

@Service
public class AcademicInfoServiceImpl implements AcademicInfoService {

    @Autowired
    private AcademicInfoMapper academicInfoMapper;

    @Autowired
    private AdmissionInfoMapper admissionInfoMapper;

    @Autowired
    private ChangeStuInfoDetailMapper changeStuInfoDetailMapper;

    @Autowired
    private NewGraduationInfoMapper newGraduationInfoMapper;
    @Autowired
    private Documents4jUtil documents4jUtil;

    @Autowired
    private ArchivalInfoMapper archivalInfoMapper;

    @Override
    public Page<AcademicInfo> getAcademicInfoPage(AcademicInfoVo academicInfoVo, Page<AcademicInfo> page) {
        // 获取分页结果
        Page<AcademicInfo> qualificationInfoPage = academicInfoMapper.getAcademicInfoPage(academicInfoVo, page);
        return qualificationInfoPage;
    }

    @Override
    public boolean batchSave(List<AcademicInfo> academicInfoList) {
        if (academicInfoList == null || academicInfoList.isEmpty()) {
            return false;
        }
        return academicInfoMapper.batchInsert(academicInfoList) > 0;
    }

    @Override
    public int batchUpdateById(AcademicInfoVo academicInfoVo, List<String> ids) {
        academicInfoVo.setIsGroupPage(true);
        return academicInfoMapper.batchUpdateById(academicInfoVo, ids);
    }

    @Override
    public void approval(List<AdmissionInfo> admissionInfoList, String transferState, String officeId, String belonging, String transferRemarks, String source) {
        // 参数校验
        if (CollectionUtils.isEmpty(admissionInfoList)) {
            throw new IllegalArgumentException("审批数据不能为空");
        }
        if ("3".equals(transferState)) {
            // 审批通过逻辑
            List<AcademicInfo> academicInfoList = admissionInfoList.stream()
                    .map(info -> {
                        AcademicInfo academicInfo = new AcademicInfo();
                        BeanUtils.copyProperties(info, academicInfo);
                        academicInfo.setBatch(info.getPcmc());
                        academicInfo.setYear(info.getYear());
                        academicInfo.setAdmissionNum(info.getZkzh());
                        academicInfo.setName(info.getXm());

                        if (info.getLqzy() != null && !info.getLqzy().isEmpty()) {
                            academicInfo.setAdmissionMajor(info.getLqzy());
                        } else {
                            academicInfo.setAdmissionMajor(info.getZymc());
                        }
                        if (info.getKsh() != null && !info.getKsh().isEmpty()) {
                            academicInfo.setExamineeNum(info.getKsh());
                        } else {
                            academicInfo.setExamineeNum(info.getZh());
                        }
                        if (info.getXh() != null && !info.getXh().isEmpty()) {
                            academicInfo.setStudentId(info.getXh());
                        } else if (info.getZxshxh() != null && !info.getZxshxh().isEmpty()) {
                            academicInfo.setStudentId(info.getZxshxh());
                        } else {
                            academicInfo.setStudentId(info.getStudentId());
                        }
                        if (info.getXb() != null && !info.getXb().isEmpty()) {
                            academicInfo.setGender(info.getXb());
                        } else {
                            academicInfo.setGender(info.getXbmc());
                        }

                        academicInfo.setSource(source);
                        academicInfo.setDelFlag("1");
                        academicInfo.setStatus("1");
                        academicInfo.setOfficeId(officeId);
                        academicInfo.setBelonging(belonging);  //表示录取信息
                        return academicInfo;
                    })
                    .collect(Collectors.toList());
            batchSave(academicInfoList);
            assignment(admissionInfoList, transferState, belonging);

        } else if ("4".equals(transferState)) {
            // 审批驳回逻辑
            List<String> ids = admissionInfoList.stream()
                    .map(item -> item.getStudentId())
                    .collect(Collectors.toList());

            assignmentState(ids, belonging, transferRemarks);

        }

    }

    @Override
    public AcademicInfo getAcademicInfoInfoById(String id) {
        return academicInfoMapper.getTemplateInfoById(id);
    }

    @Override
    public void print(String type, String id, HttpServletResponse response) {

        // 参数校验
        if (type == null || id == null || response == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        String outputPath = "";
        String fileName = "";
        String pdfName = "";
        URL resourceUrl = null;
        LocalDate now = null;
        AcademicInfo academicInfo;
        Map<String, Object> map = new HashMap<>();
        switch (type) {
            // 录取证明
            case "1":
                resourceUrl = getClass().getClassLoader().getResource("templates/wordFtl/proofOfAdmission.docx");
                if (resourceUrl == null) {
                    throw new RuntimeException("模板文件未找到");
                }

//            AcademicInfo academicInfo = academicInfoMapper.getTemplateInfoById(id));
                academicInfo = academicInfoMapper.getTemplateInfoById("38");

                map.put("caseName", "吉林省2016年成人高校统一招生考试录取名单");
                map.put("reference", "2016-JX13-0010");
                map.put("name", academicInfo.getName());
                map.put("nameB", StringUtil.isNotEmpty(academicInfo.getName()));
                map.put("gender", academicInfo.getGender());
                map.put("genderB", StringUtil.isNotEmpty(academicInfo.getGender()));
                map.put("studentId", academicInfo.getStudentId());
                map.put("studentIdB", StringUtil.isNotEmpty(academicInfo.getStudentId()));
                map.put("admissionNum", academicInfo.getAdmissionNum());
                map.put("admissionNumB", StringUtil.isNotEmpty(academicInfo.getAdmissionNum()));
                map.put("admissionMajor", academicInfo.getAdmissionMajor());
                map.put("admissionMajorB", StringUtil.isNotEmpty(academicInfo.getAdmissionMajor()));

                now = LocalDate.now();
                map.put("year", now.getYear());
                map.put("month", now.getMonthValue());
                map.put("day", now.getDayOfMonth());

                fileName = academicInfo.getName() + "的录取证明";
                outputPath = System.getProperty("java.io.tmpdir") + fileName + ".docx";

                wordToPdf(outputPath, resourceUrl, academicInfo, map, fileName, response);
                break;
            //学历证明
            case "2":
                resourceUrl = getClass().getClassLoader().getResource("templates/wordFtl/academicQualifications.docx");
                if (resourceUrl == null) {
                    throw new RuntimeException("模板文件未找到");
                }

//            AcademicInfo academicInfo = academicInfoMapper.getTemplateInfoById(id));
                academicInfo = academicInfoMapper.getTemplateInfoById("38");
                map.put("caseName", academicInfo.getCaseName());
                map.put("reference", academicInfo.getReference());
                map.put("name", academicInfo.getName());
                map.put("nameB", StringUtil.isNotEmpty(academicInfo.getName()));
                map.put("gender", academicInfo.getGender());
                map.put("genderB", StringUtil.isNotEmpty(academicInfo.getGender()));
                map.put("studentId", academicInfo.getStudentId());
                map.put("studentIdB", StringUtil.isNotEmpty(academicInfo.getStudentId()));
                map.put("admissionNum", academicInfo.getAdmissionNum());
                map.put("admissionNumB", StringUtil.isNotEmpty(academicInfo.getAdmissionNum()));
                map.put("admissionMajor", academicInfo.getAdmissionMajor());
                map.put("admissionMajorB", StringUtil.isNotEmpty(academicInfo.getAdmissionMajor()));

                now = LocalDate.now();
                map.put("year", now.getYear());
                map.put("month", now.getMonthValue());
                map.put("day", now.getDayOfMonth());
                fileName = academicInfo.getName() + "的学历证明";
                outputPath = System.getProperty("java.io.tmpdir") + fileName + ".docx";
                wordToPdf(outputPath, resourceUrl, academicInfo, map, fileName, response);
                break;
            case "3":
                resourceUrl = getClass().getClassLoader().getResource("templates/wordFtl/degreeCertificate.docx");
                if (resourceUrl == null) {
                    throw new RuntimeException("模板文件未找到");
                }
                academicInfo = academicInfoMapper.getTemplateInfoById("38");
                map.put("caseName", academicInfo.getCaseName());
                map.put("reference", academicInfo.getReference());
                map.put("name", academicInfo.getName());
                map.put("nameB", StringUtil.isNotEmpty(academicInfo.getName()));
                map.put("gender", academicInfo.getGender());
                map.put("genderB", StringUtil.isNotEmpty(academicInfo.getGender()));
                map.put("studentId", academicInfo.getStudentId());
                map.put("studentIdB", StringUtil.isNotEmpty(academicInfo.getStudentId()));
                map.put("admissionNum", academicInfo.getAdmissionNum());
                map.put("admissionNumB", StringUtil.isNotEmpty(academicInfo.getAdmissionNum()));
                map.put("admissionMajor", academicInfo.getAdmissionMajor());
                map.put("admissionMajorB", StringUtil.isNotEmpty(academicInfo.getAdmissionMajor()));

                now = LocalDate.now();
                map.put("year", now.getYear());
                map.put("month", now.getMonthValue());
                map.put("day", now.getDayOfMonth());
                fileName = academicInfo.getName() + "的学位证明";
                outputPath = System.getProperty("java.io.tmpdir") + fileName + ".docx";
                wordToPdf(outputPath, resourceUrl, academicInfo, map, fileName, response);
                break;
            default:
                throw new IllegalArgumentException("未知的打印类型");
        }
    }

    private void wordToPdf(String outputPath, URL resourceUrl, AcademicInfo academicInfo, Map<String, Object> map, String fileName, HttpServletResponse response) {
        try (XWPFTemplate template = XWPFTemplate.compile(resourceUrl.getFile())) {
            template.render(map);
            template.writeToFile(outputPath);
            String path = documents4jUtil.convertWordToPdf(outputPath) + fileName + ".pdf";
            // 帮我把pdf文件通过response返回给前端
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".pdf\"");
            java.nio.file.Files.copy(java.nio.file.Paths.get(path), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException("模板生成失败: " + e.getMessage(), e);
        }
    }


    private void assignment(List<AdmissionInfo> admissionInfos, String transferState, String belonging) {
        if (belonging.equals("1")) {
            admissionInfoMapper.batchUpdateAdmissionInfo(admissionInfos, transferState);
        } else if (belonging.equals("2")) {
            changeStuInfoDetailMapper.batchUpdateChange(admissionInfos, transferState);
        } else if (belonging.equals("3")) {
            archivalInfoMapper.batchUpdateArchivalInfo(admissionInfos, transferState);
        } else if (belonging.equals("4")) {
            newGraduationInfoMapper.batchUpdateGraduationInfo(admissionInfos, transferState);
        }
    }

    private void assignmentState(List<String> ids, String belonging, String transferRemarks) {
        if (belonging.equals("1")) {
            AdmissionInfo admissionInfo = new AdmissionInfo();
            admissionInfo.setTransferState(4); // 驳回状态
            admissionInfo.setTransferRemarks(transferRemarks);
            admissionInfoMapper.batchUpdateById(ids, admissionInfo);
        } else if (belonging.equals("2")) {
            ChangeStuInfo changeStuInfo = new ChangeStuInfo();
            changeStuInfo.setTransferState(4); // 驳回状态
            changeStuInfo.setTransferRemarks(transferRemarks);
            changeStuInfoDetailMapper.batchUpdateById(ids, changeStuInfo);
        } else if (belonging.equals("3")) {
            ArchivalInfo archivalInfo = new ArchivalInfo();
            archivalInfo.setTransferState(4); // 驳回状态
            archivalInfo.setTransferRemarks(transferRemarks);
            archivalInfoMapper.batchUpdateById(ids, archivalInfo);
        } else if (belonging.equals("4")) {
            NewGraduationInfo graduationInfo = new NewGraduationInfo();
            graduationInfo.setTransferState(4); // 驳回状态
            graduationInfo.setTransferRemarks(transferRemarks);
            newGraduationInfoMapper.batchUpdateById(ids, graduationInfo);
        }

    }
}
